package edu.umn.contactviewer;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import edu.umn.contactviewer.models.Contact;
import edu.umn.contactviewer.utils.FileOps;
import edu.umn.contactviewer.utils.JsonSerializer;

/** Displays a list of contacts.
 *
 */
public class ContactListActivity extends ListActivity implements View.OnClickListener {
	
	ArrayList<Contact> contacts;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list);
        ToolbarConfig toolbarConfig = new ToolbarConfig(this, "Contacts");
        toolbarConfig.getToolbarRightButton().setText("Add");
        
        // make some contacts
        /*
        ArrayList<Contact> contacts = new ArrayList<Contact>();
        contacts.add(new Contact("Malcom Reynolds")
            .setEmail("mal@serenity.com")
            .setTitle("Captain")
            .setPhone("612-555-1234")
            .setTwitterId("malcomreynolds"));
        contacts.add(new Contact("Zoe Washburne")
            .setEmail("zoe@serenity.com")
            .setTitle("First Mate")
            .setPhone("612-555-5678")
            .setTwitterId("zoewashburne"));
        contacts.add(new Contact("Hoban Washburne")
            .setEmail("wash@serenity.com")
            .setTitle("Pilot")
            .setPhone("612-555-9012")
            .setTwitterId("wash"));
        contacts.add(new Contact("Jayne Cobb")
            .setEmail("jayne@serenity.com")
            .setTitle("Muscle")
            .setPhone("612-555-3456")
            .setTwitterId("heroofcanton"));
        contacts.add(new Contact("Kaylee Frye")
            .setEmail("kaylee@serenity.com")
            .setTitle("Engineer")
            .setPhone("612-555-7890")
            .setTwitterId("kaylee"));
        contacts.add(new Contact("Simon Tam")
            .setEmail("simon@serenity.com")
            .setTitle("Doctor")
            .setPhone("612-555-4321")
            .setTwitterId("simontam"));
        contacts.add(new Contact("River Tam")
            .setEmail("river@serenity.com")
            .setTitle("Doctor's Sister")
            .setPhone("612-555-8765")
            .setTwitterId("miranda"));
        contacts.add(new Contact("Shepherd Book")
            .setEmail("shepherd@serenity.com")
            .setTitle("Shepherd")
            .setPhone("612-555-2109")
            .setTwitterId("shepherdbook"));
        */
        Context ctxt = this.getBaseContext();
        String rawJson = FileOps.readFile(ctxt);
        contacts = new ArrayList<Contact>();
        if(rawJson != null){
            contacts = JsonSerializer.parseContacts(rawJson);
            Collections.sort(contacts);
        }

        // initialize the list view
        setListAdapter(new ContactAdapter(this, R.layout.list_item, contacts));
        ListView lv = getListView();
        lv.setTextFilterEnabled(true);
        
        // handle the item click events
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("contact", (Contact) getListAdapter().getItem(position));
                Intent intent = new Intent();
                intent.setClass(ContactListActivity.this, ContactInfoActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
                }
            }
        );

        findViewById(R.id.toolbar_right_button).setOnClickListener(this);
        findViewById(R.id.toolbar_back_button).setOnClickListener(this);
        
        registerForContextMenu( lv );
    }

    public void onClick(View view) {
        if (view.getId() == R.id.toolbar_right_button) {
            Bundle bundle = new Bundle();
            bundle.putSerializable("contact", new Contact());
            Intent intent = new Intent();
            intent.setClass(ContactListActivity.this, ContactEditActivity.class);
            intent.putExtras(bundle);
            startActivity(intent);
        }
        else if (view.getId() == R.id.toolbar_back_button) {
            Intent intent = new Intent(this, HomeActivity.class);
            startActivity(intent);
            overridePendingTransition( R.anim.slide_in_right, R.anim.slide_out_right );
        }
    }
    
    public void onCreateContextMenu(ContextMenu menu, View v,
		            ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.context_menu, menu);
		}
    
    public boolean onContextItemSelected(MenuItem item) {
    	Context ctxt = this.getBaseContext();
    	
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        
        contacts.remove( (int)info.id );
        
        FileOps.writeFile(ctxt, JsonSerializer.toJSON(contacts));
        
        setListAdapter(new ContactAdapter(this, R.layout.list_item, contacts));
        
        return false;
    }

    /* We need to provide a custom adapter in order to use a custom list item view.
     */
    public class ContactAdapter extends ArrayAdapter<Contact> {
    
        public ContactAdapter(Context context, int textViewResourceId, List<Contact> objects) {
            super(context, textViewResourceId, objects);
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = getLayoutInflater();
            View item = inflater.inflate(R.layout.list_item, parent, false);
            
            Contact contact = getItem(position);
            ((TextView)item.findViewById(R.id.item_name)).setText(contact.getName());
            ((TextView)item.findViewById(R.id.item_title)).setText(contact.getTitle() + " ");
            ((TextView)item.findViewById(R.id.item_phone)).setText(contact.getPhone());
            
            return item;
        }
    }
    
}